package com.zzw.springboot.utils;

import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zzw.springboot.entity.User;
import com.zzw.springboot.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Author zzw2000
 * @Date 2022年05月18日 15:20
 * @Description token工具类
 */
@Component
@Slf4j
public class JwtUtils {

    private static IUserService staticUserService;
    @Resource
    private IUserService userService;

    @PostConstruct
    public void setUserService() {
        staticUserService = userService;
    }

    /**
     * 生成token
     *
     * @param userId
     * @return
     */
    public static String generateToken(String userId, String password) {
        return JWT.create().withAudience(userId) //将id保存到token中
                .withExpiresAt(DateUtil.offsetHour(new Date(), 1)) //1小时后过期
                .sign(Algorithm.HMAC256(password)); //以password作为token的密钥
    }

    /**
     * 获取当前用户数据
     *
     * @return
     */
    public static User getCurrentUser() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StringUtils.isNotBlank(token)) {
                String userId = JWT.decode(token).getAudience().get(0);
                return staticUserService.getById(Integer.valueOf(userId));
            }
        } catch (Exception e) {
            log.error("从token中获取当前用户信息失败" + e.getMessage());
            return null;
        }
        return null;
    }
}
